<template>
  <div>
    <!--面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图-->
    <el-card>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUsersList">
            <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>

      <!--用户列表区-->
      <el-table border :stripe="true"
                :data="userList"
                style="width: 100%">
        <el-table-column
          type="index">
        </el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="180">
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="180">
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="电话">
        </el-table-column>
        <el-table-column
          prop="role_name"
          label="角色">
        </el-table-column>
        <el-table-column
          label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state" @change="changeState(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作">
          <template slot-scope="scope" width="180px">
            <el-button type="primary" icon="el-icon-edit" size="min" @click="showEditDialog(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="min" @click="deleteUser(scope.row.id)"></el-button>

            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="min" @click="setRole(scope.row)"></el-button>
            </el-tooltip>

          </template>

        </el-table-column>

      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalNum">
      </el-pagination>
    </el-card>


    <!--添加用户的对话框-->

    <el-dialog title="添加用户"
               :visible.sync="addDialogVisible"
               width="30%" @close="addDialogClosed">
      <!--表单主体-->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>

      </el-form>

      <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
    </el-dialog>
    <!--添加编辑对话框-->

    <el-dialog
      title="修改窗口"
      :visible.sync="editDialogVisible"
      width="30%" @close="editDialogClose">
      <el-form :model="editForm" :rules="editFormRules" ref="editRuleForm" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editUser">确 定</el-button>
  </span>
    </el-dialog>
    <!--分配角色的对话框-->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="30%" @close="setRoleDialogColsed">
      <div>
        <p>当前的用户:{{ userInfo.username }}</p>
        <p>当前的角色:{{ userInfo.role_name }}</p>
        <p>分配角色:
          <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="setRoleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="setRoleInfo">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Users",
  data() {
    var checkEmail = (rule, value, callback) => {
      //验证邮箱正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        callback()
      } else {
        return callback(new Error('请输入正确的邮箱'))
      }
    }
    var checkMobile = (rule, value, callback) => {
      const redMobile = /[0-9]{8,11}/
      if (redMobile.test(value)) {
        callback()
      } else {
        return callback(new Error('请输入正确的号码'))
      }
    }

    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      totalNum: 0,
      addDialogVisible: false,
      editDialogVisible: false,
      editForm: {},
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addFormRules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 3, max: 10, message: '请输入3到10个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 10, message: '请输入6到10个字符', trigger: 'blur'}
        ],
        email: [
          {required: true, validator: checkEmail, trigger: 'blur'}
        ],
        mobile: [
          {required: true, validator: checkMobile, trigger: 'blur'}
        ]
      },
      editFormRules: {
        email: [
          {required: true, validator: checkEmail, trigger: 'blur'}
        ],
        mobile: [
          {required: true, validator: checkMobile, trigger: 'blur'}
        ]
      },

      //控制角色对话框的显示与隐藏
      setRoleDialogVisible: false,
      userInfo: {},
      //所有角色的列表
      rolesList: [],
      selectRoleId: ''
    }
  },
  created() {
    this.getUsersList();
  },
  methods: {
    async getUsersList() {
      const {data: res} = await this.$http.get('users', {params: this.queryInfo});
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      } else {
        this.userList = res.data.users
        this.totalNum = res.data.total
      }

    },
    handleSizeChange(newSize) {
      console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUsersList();
    },
    handleCurrentChange(newPage) {
      console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getUsersList();
    },
    async changeState(state) {
      console.log(state.mg_state)
      const {data: res} = await this.$http.put(`users/${state.id}/state/${state.mg_state}`)
      if (res.meta.status !== 200) {
        state.mg_state = !state.mg_state
        this.$message.error('状态设置失败')
      } else {
        this.$message.success('状态设置成功')
      }
    },
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (valid) {
          console.log(this.addForm)
          const {data: res} = await this.$http.post('/users', this.addForm)
          console.log(res)
          if (res.meta.status === 201) {
            this.$message.success(res.meta.msg)
            this.addDialogVisible = false
            this.getUsersList()
          } else {
            this.$message.error(res.meta.msg)
          }
        } else {
          return
        }
      })
    },
    async showEditDialog(id) {

      console.log(id)
      const {data: res} = await this.$http.get(`/users/${id}`)
      if (res.meta.status === 200) {
        this.editDialogVisible = true
        this.editForm = res.data;
        // console.log(res.data);
      } else {
        this.$message.error('请求失败')
      }
    },
    editUser() {
      this.$refs.editRuleForm.validate(async (valid) => {
        if (valid) {
          const {data: res} = await this.$http.put('/users/' + this.editForm.id, {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          })
          if (res.meta.status === 200) {
            this.$message.success(res.meta.msg);
            this.getUsersList()
            this.editDialogVisible = false
          }
        }
      })

    },
    editDialogClose() {
      this.$refs.editRuleForm.resetFields();
    },
    async deleteUser(id) {
      const confirm1 = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      //console.log(res)
      if (confirm1 === 'confirm') {
        const {data: res} = await this.$http.delete('users/' + id)
        console.log(res);
        if (res.meta.status === 200) {
          this.getUsersList()
          this.$message({
            type: 'success',
            message: '删除成功'
          });
        }
      } else {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      }

    },
    async setRole(role) {
      this.userInfo = role
      const {data: res} = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        this.$message.error('请求失败')
      } else {
        console.log(res.data)
        this.rolesList = res.data
      }
      this.setRoleDialogVisible = true
    },
    async setRoleInfo() {
      if (!this.selectRoleId) {
        this.$message.info('请选择角色');
      } else {
        const {data: res} = await this.$http.put(`users/${this.userInfo.id}/role`, {rid: this.selectRoleId});
        if (res.meta.status !== 200) {

        } else {
           this.getUsersList();
           this.setRoleDialogVisible = false
        }
      }
    },
    setRoleDialogColsed(){
      this.selectRoleId=''
      this.userInfo=[]
    }
  }
}
</script>

<style lang="less" scoped>
.el-breadcrumb {
  font-size: 14px;
  line-height: 2;
}

.el-row {
  line-height: 60px;
}

.el-table {
  margin-top: 15px;
}
</style>
